package com.letoken.platform.app.job;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson2.JSON;
import com.letoken.platform.pub.util.HttpClientUtil;
import com.letoken.platform.repo.admin.dao.AdminSwapConfigMapper;
import com.letoken.platform.repo.admin.po.AdminSwapConfig;
import com.letoken.platform.repo.app.po.Token;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;

@Component
@Slf4j
public class UpdateCAPorUSDTRateJob {
    //udst数量
    private static String usdtUrl="https://api.bscscan.com/api" +
            "?module=account" +
            "&action=tokenbalance" +
            "&contractaddress=0x55d398326f99059fF775485246999027B3197955" +
            "&address=0xeF2058BFBd3A65A87045b73d11588587F0337526" +
            "&tag=latest" +
            "&apikey=UE17I7HPJJ5TMJYWYWYMQQAP85YGJTQCT4";

    //cap数量
    private static String capUrl="https://api.bscscan.com/api?module=account" +
            "&action=tokenbalance" +
            "&contractaddress=0x6ef91B8332F3f3Fa1E87573Da5DE2704ac84dFf4" +
            "&address=0xeF2058BFBd3A65A87045b73d11588587F0337526" +
            "&tag=latest" +
            "&apikey=UE17I7HPJJ5TMJYWYWYMQQAP85YGJTQCT4";

    @Resource
    AdminSwapConfigMapper adminSwapConfigMapper;

    @XxlJob("updateCAPorUSDTRate")
    public  void updateCAPorUSDTRate() throws Exception {
        log.info("start updateCAPorUSDTRate");
        try {
            String usetStr = HttpClientUtil.sendGet(usdtUrl,null,null);
            BigDecimal usdt =  new BigDecimal(JSONUtil.toBean(usetStr,JSONObject.class).get("result").toString());
            String capStr =  HttpClientUtil.sendGet(capUrl,null,null);
            BigDecimal cap =  new BigDecimal(JSONUtil.toBean(capStr,JSONObject.class).get("result").toString());
            //u:cap
            BigDecimal rate = usdt.divide(cap,10, RoundingMode.HALF_UP);

            AdminSwapConfig adminSwapConfig = adminSwapConfigMapper.selectById(1);
            adminSwapConfig.setPrice(rate);
            adminSwapConfig.setUpdateTime(LocalDateTime.now());
            adminSwapConfig.updateById();

            AdminSwapConfig adminSwapConfig2 = adminSwapConfigMapper.selectById(2);
            adminSwapConfig2.setPrice( BigDecimal.ONE.divide(rate,10, RoundingMode.HALF_UP));
            adminSwapConfig2.setUpdateTime(LocalDateTime.now());
            adminSwapConfig2.updateById();


            Token token = new Token();
            token.setId(4);
            token.setUsdPrice(rate.toString());
            token.updateById();
        }catch (Exception e){
         log.error("execute updateCAPorUSDTRate error;", e);
        }
        log.info("end updateCAPorUSDTRate");
    }

}
